package edu.sctu;


import edu.sctu.User;
import edu.sctu.UserDao;
import edu.sctu.DbUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;

/**
 * 登录Servlet
 */
public class LoginServlet extends HttpServlet {

    DbUtil dbUtil = new DbUtil();
    UserDao userDao = new UserDao();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        HttpSession session=request.getSession();


        //用户登录表单的参数
        String userName = request.getParameter("username");
        String password = request.getParameter("password");

        Connection connection = null;
        try {
            connection=dbUtil.getCon();
            User user = new User(userName,password);//用户表单数据
            User currentUser = userDao.login(connection,user);//登录验证

            if (currentUser == null){
//                request.setAttribute("user",user);//登录失败后，将失败的信息继续传入页面显示
                request.setAttribute("error","用户名或密码错误！");
                request.getRequestDispatcher("login.jsp").forward(request,response);

                System.out.println("登录失败");
            }else {
                System.out.println("登录成功");
                session.setAttribute("isLogin","true");//设置登录成功
                session.setAttribute("currentUser",currentUser);
                response.sendRedirect("/userList");//登录成功后跳转到userList.jsp页面
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                //数据库关闭
                dbUtil.closeCon(connection);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


    }
}